package com.wyb.fastdfs.service.impl;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.wyb.fastdfs.config.ElasticSearchConfig;
import com.wyb.fastdfs.constant.EsConstant;
import com.wyb.fastdfs.dto.es.FileEsModel;
import com.wyb.fastdfs.entity.FileEntity;
import com.wyb.fastdfs.mapper.FileMapper;
import com.wyb.fastdfs.service.FileService;

import lombok.extern.slf4j.Slf4j;

/**
 * @Author:wangyibo
 * @Date 2021年8月12日
 * @Version:1.0
 * @Description:TODO
 */
@Service
@Slf4j
public class FileServiceImpl implements FileService {

	@Autowired
	private FileMapper fileMapper;

	@Autowired
	RestHighLevelClient restHighLevelClient;

	@Override
	public boolean verify(String fileId) throws IOException {
		// TODO Auto-generated method stub
		List<FileEsModel> fileEsModels = new ArrayList<>();

		// 组装成模型
		FileEsModel fileEsModel = new FileEsModel();
		FileEntity entity = fileMapper.searchFileById(fileId);
		fileEsModel.setAuthor(entity.getAuthor());
		fileEsModel.setCategoryId(entity.getCategoryId());
		fileEsModel.setFileId(entity.getId());
		fileEsModel.setFileTitle(entity.getName());
		fileEsModels.add(fileEsModel);

		// 保存到es
		// 1.给es中建立索引和映射关系
		// 2.给es中保存数据
		BulkRequest bulkRequest = new BulkRequest();
		for (FileEsModel model : fileEsModels)
			try {
				{
					// 构造保存请求
					IndexRequest indexRequest = new IndexRequest(EsConstant.FILE_INDEX);
					indexRequest.id(model.getFileId());
					String jsonString = JSON.toJSONString(model);
					indexRequest.source(jsonString, XContentType.JSON);
					bulkRequest.add(indexRequest);
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, ElasticSearchConfig.COMMON_OPTION);
		boolean b = bulk.hasFailures();
		List<String> collect = Arrays.stream(bulk.getItems()).map(item -> {
			return item.getId();
		}).collect(Collectors.toList());
		log.error("批量上传是否错误:{}", b);
		return !b;
	}

	@Override
	public List<FileEntity> fileEntities() {
		// TODO Auto-generated method stub
		return fileMapper.getAll();
	}

}
